<template>
    <div>
        <!-- 搜索卡片 查询条件：响应新闻标题、响应用户名、响应用户真实姓名、审核状态 -->
        <el-card>
            <el-form :model="queryForm" :inline="true">
                <el-form-item label="响应新闻标题">
                    <el-input type="text" placeholder="请输入新闻标题" v-model="queryForm.newsTitle" size="small"></el-input>
                </el-form-item>
                <el-form-item label="响应用户名">
                    <el-input type="text" placeholder="请输入响应用户名" v-model="queryForm.createBy" size="small"></el-input>
                </el-form-item>
                <el-form-item label="响应用户真实姓名">
                    <el-input type="text" placeholder="请输入响应用户真实姓名" v-model="queryForm.realname" size="small"></el-input>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-select v-model="queryForm.status" size="small">
                        <el-option :value="-1" label="拒绝通过"></el-option>
                        <el-option :value="0" label="等待审核"></el-option>
                        <el-option :value="1" label="审核通过"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
                    <el-button size="small" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 数据卡片 -->
        <el-card class="mt12" style="margin-top: 10px">
            <div class="handel-btns">
                <div class="left-btns">
                    <el-button size="small" icon="el-icon-plus" type="primary" plain @click="handleAdd()">新增</el-button>
                    <el-button size="small" icon="el-icon-delete" type="danger" plain @click="handleBatchDelete()">删除</el-button>
                </div>
            </div>
            <!-- 数据表格 -->
            <el-table
            :data="newsList"
            v-loading="loading"
            border
            fit
            :header-cell-style="{background:'#f8f8f9',color:'#5a516e',padding:'10px 0px'}"
            :cell-style="{padding:'5px 0px'}"
            @selection-change="handleSelectionChange"
            style="margin: 10px 0">
                <el-table-column type="selection" align="center" width="50px"></el-table-column>
                <el-table-column align="center" label="ID" width="80" prop="ID">
                    <template slot-scope="scope">
                    {{ scope.row.id }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="响应新闻标题" prop="newsTitle" width="200" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                    {{ scope.row.newsTitle }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="响应内容" prop="content" width="300" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                    {{ scope.row.content }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="响应用户真实姓名" prop="realname" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                    {{ scope.row.realname }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="响应用户名" prop="createBy" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                    {{ scope.row.createBy }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="响应时间" prop="createTime">
                    <template slot-scope="scope">
                    {{ scope.row.createTime }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="审核状态" prop="status">
                    <template slot-scope="scope">
                        <el-tag  type="danger" v-if="scope.row.status == -1">拒绝通过</el-tag>
                        <el-tag v-if="scope.row.status == 0">等待审核</el-tag>
                        <el-tag type="success" v-if="scope.row.status == 1">审核通过</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" plain icon="el-icon-edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                        <el-button size="small" type="danger" plain icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                    :current-page="queryForm.pageNum" 
                    :page-size="queryForm.pageSize"
                    :total="total"
                    :page-sizes="[10,20,50,100]"
                    layout="total,sizes,prev,pager,next"
                    @current-change='handleCurrentChange'
                    @size-change='handleSizeChange'>
                </el-pagination>
        </el-card>
        <!-- 新增和编辑弹窗 -->
        <el-dialog :title="title" :visible.sync="show"  width="50%">
            <el-form :model="submitForm" :rules="dataRule" ref="submitForm" inline>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="新闻ID" prop="newsId">
                            <el-input v-model="submitForm.newsId" placeholder="请输入新闻ID" maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="审核状态" prop="status">
                            <el-select v-model="submitForm.status" placeholder="请选择">
                                <el-option :value="-1" label="拒绝通过"></el-option>
                                <el-option :value="0" label="等待审核"></el-option>
                                <el-option :value="1" label="审核通过"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="内容" prop="content" class="form-item-content">
                            <quill-editor ref="myQuillEditor" v-model="submitForm.content" class="editor" :options="editorOption" @focus="quillEditorFocus($event)"/>
                        </el-form-item>
                    </el-col>
                </el-row>

                </el-form>
                <!-- 富文本编辑器中的上传图片控件 -->
                <el-upload
                    class="avatar-uploader-img"
                    :action="uploadUrl"
                    :show-file-list="false"
                    :on-success="uploadImgSuccess"
                    :before-upload="beforeUploadImg"
                    :on-error="uploadImgError"
                    :headers="headers"
                    :data="{'pathName':''}"
                />
            <div class="dialog-footer" slot="footer" style="margin-right:40px;">
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { selectAll,getRespond,addRespond,updateRespond,delRespond } from '@/api/respond'
    const toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
        ['blockquote', 'code-block'], // 引用  代码块
        [{ header: 1 }, { header: 2 }], // 1、2 级标题
        [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
        [{ script: 'sub' }, { script: 'super' }], // 上标/下标
        [{ indent: '-1' }, { indent: '+1' }], // 缩进
        // [{'direction': 'rtl'}],                         // 文本方向
        [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
        [{ font: [] }], // 字体种类
        [{ align: [] }], // 对齐方式
        ['clean'], // 清除文本格式
        // ['link', 'image', 'video'] // 链接、图片
        ['link', 'image'] // 链接、图片
    ]
    export default {
        name:'Respond',
        data(){
            return{
                loading: true,
                userId:this.$Cookie.get("userId"),
                submitForm:{},
                title:"新增",
                show:false,
                total:120,
                queryForm:{
                    pageNum:1,
                    pageSize:10
                },
                selectList:[],
                newsList:[],
                headers:{
                    Authorization: 'Bearer ' + this.$Cookie.get('login-token')
                },
                uploadUrl: '/img-api/img/upload/imgs',
                editorOption: { // 编辑框操作事件
                    theme: 'snow', // or 'bubble'
                    placeholder: '请输入响应内容...',
                    modules: {
                        toolbar: {
                            container: toolbarOptions,
                            handlers: {
                                image: function(value) { // 上传图片
                                    if (value) {
                                        document.querySelector('.avatar-uploader-img input').click() // 触发input框选择文件
                                    } else {
                                    this.quill.format('image', false)
                                    }
                                },
                                link: function(value) { // 添加链接
                                    if (value) {
                                    var href = prompt('请输入链接地址：')
                                    this.quill.format('link', href)
                                    } else {
                                    this.quill.format('link', false)
                                    }
                                }
                            }
                        }
                    }    
                },
                submitForm: {
                    id: '',
                    title: '',
                    content: '',
                    flag: ''
                }    
            }
        },
        computed: {
            dataRule () {
                return {
                    newsId: [//新闻ID
                    { required: true, message: '请输入标题', trigger: 'blur' }
                    ],
                    content: [//内容
                    { required: true, message: '请输入内容', trigger: 'blur' }
                    ]
                }
            }
        },
        //创建网页后查询调用数据
        created(){
            this.getList()
        },
        methods:{
            //调用接口提交数据 - 进行添加和编辑操作的弹窗
            handleSubmit(){
                this.$refs['submitForm'].validate((valid)=>{
                    if(valid){
                        if(this.submitForm.id){
                            this.submitForm.updateBy = this.$Cookie.get("username")
                            updateRespond(this.submitForm).then(res=>{
                                this.show = false
                                this.submitForm = {}
                                this.getList()
                            }).catch(err=>{console.log(err)})
                        }else{
                            this.submitForm.userId = this.$Cookie.get("userId")
                            this.submitForm.createBy = this.$Cookie.get("username")
                            addRespond(this.submitForm).then(res=>{
                                this.show = false
                                this.submitForm = {}
                                this.getList()
                            }).catch(err=>{console.log(err)})
                        }
                        this.show = false
                        this.submitForm = {}
                        this.getList()
                    }
                })
            },
            //重置搜索
            handleReset(){
                this.queryForm = {
                    pageNum:1,
                    pageSize:10
                }
                this.getList()
            },
            //按条件搜索
            handleSearch(){
                this.queryForm.pageNum = 1
                this.getList()
            },
            //修改每页大小
            handleSizeChange(pageSize){
                this.queryForm.pageSize = pageSize
                this.queryForm.pageNum = 1
                this.getList()
            },
            //当前页修改
            handleCurrentChange(pageNum){
                this.queryForm.pageNum = pageNum
                this.getList()
            },
            //调用接口分页查询用户数据
            getList(){
                this.loading = true
                console.log("-------------------------------------------",this.queryForm)
                selectAll(this.queryForm).then(res=>{
                    this.newsList = res.data.records
                    this.total = res.data.total
                    this.loading = false
                }).catch(err=>{})
                
            },
            //删除 - 调用接口删除记录
            handleDelete(ids){
                this.$confirm("你确定删除id为"+ids+"的记录吗？","提示",{
                    cancelButtonText:"取消",
                    confirmButtonText:"确定",
                    type:"warning"
                }).then(()=>{
                    //调接口删除
                    delRespond({ids:ids,sender:this.$Cookie.get("username")}).then(res => {
                        //提示删除成功
                        this.$message("删除成功")
                        //刷新列表
                        this.getList()
                    }).catch(err=>{
                        console.log(err)
                    })
                }).catch(()=>{})
            },
            //添加 - 打开添加弹窗
            handleAdd(){
                this.show = true
                this.title = "新增"
                this.submitForm={}
            },
            //取消 - 关闭弹窗
            handleCancel(){
                this.show = false
            },
            //编辑 - 打开编辑弹窗
            handleEdit(id){
                getRespond(id).then(res=>{
                    //调接口获取最新数据
                    this.title = "编辑"
                    this.show = true
                    this.submitForm = res.data
                }).catch(err=>{
                    console.log(err)
                })
                
            },
            //批量删除
            handleBatchDelete(){
                if(this.selectList){
                    let ids = this.selectList.map(o => {return o.id})
                    console.log('ids---------->',ids)
                    this.handleDelete(ids)
                }
            },
            //多选
            handleSelectionChange(val){
                this.selectList = val;
            },
            beforeUploadImg(file) {//富文本图片上传前
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG，PNG, GIF 格式!')
                } else {
                    // 显示loading动画
                    this.quillUpdate = true
                }
                return isJPG
            },
            //富文本图片上传成功
            uploadImgSuccess(res, file) {
                // res为图片服务器返回的数据
                // 获取富文本组件实例
                const quill = this.$refs.myQuillEditor.quill
                console.log(res)
                //这里需要注意自己文件上传接口返回内容，我这里code=200表示上传成功，返回的文件地址：res.data.src
                if (res.code !== 200) {
                    this.$message.error(res.msg)
                } else {
                    // 获取光标所在位置
                    const length = quill.getSelection().index
                    // 插入图片  res.data为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', '/images/imgs/' + res.data)
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                }
                // loading动画消失
                this.quillUpdate = false
            },
            //富文本图片上传失败
            uploadImgError() {
                // loading动画消失
                this.quillUpdate = false
                this.$message.error('图片插入失败!')
            },
            //富文本的获得焦点事件
            quillEditorFocus(event) {
                // 在这里可以设置富文本编辑器是否可编辑
                //event.enable(false);//不可输入和编辑
                //event.enable(true);//可以输入和编辑
            },
        }
    }
</script>

<style scoped>
    .el-form-item{
        margin: 10px;
    }
    /************************************** 富文本编辑器 **************************************/
    /** 设置富文本的高度 **/
    .editor {
    line-height: normal !important;
    height: 300px;
    margin-bottom: 30px;
    }
    .ql-container {
    height: 300px !important;
    }
    /** 设置富文本的高度 **/

    /** 设置工具栏中上传图片和上传视频对应的文件上传组件样式 **/
    .avatar-uploader-img {
    height: 0;
    }
    .avatar-uploader-video {
    height: 0;
    }
    /** 设置工具栏中上传图片和上传视频对应的文件上传组件样式 **/
    ::v-deep .ql-snow .ql-tooltip[data-mode=link]::before {
    content: '请输入链接地址：';
    }
    ::v-deep .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: '保存';
    padding-right: 0px;
    }
    ::v-deep .ql-snow .ql-tooltip[data-mode=video]::before {
    content: '请输入视频地址：';
    }
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-label::before,
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: '14px';
    }
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
    content: '10px';
    }
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
    content: '18px';
    }
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
    ::v-deep .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
    content: '32px';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: '文本';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
    content: '标题1';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
    content: '标题2';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
    content: '标题3';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
    content: '标题4';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
    content: '标题5';
    }
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
    ::v-deep .ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
    content: '标题6';
    }
    ::v-deep .ql-snow .ql-picker.ql-font .ql-picker-label::before,
    ::v-deep .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: '标准字体';
    }
    ::v-deep .ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]::before,
    ::v-deep .ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]::before {
    content: '衬线字体';
    }
    ::v-deep .ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]::before,
    ::v-deep .ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]::before {
    content: '等宽字体';
    }
</style>